package main

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/influxdata/influxdb/uuid"
	"log"
	"os"
	"strconv"
	"time"
)

// WsData 消息内容
type EMQonlineData struct {
	Status     int
	UpdateTime int
}
type data struct {
	Token      string `json:"token"`
	UserId     int    `json:"user_id"`
	CustomerId int    `json:"customer_id"`
	Type       string
}

type OnlineData struct {
	Status int
	Error  error
	Data   interface{}
}

// GetClient 获取EMQ连接属性
// @params Addr string 链接地址 tcp://14.29.243.119:1883
// @params ClientID string 连接ID get_gateway_status[随机]
func GetClient(Addr string, ClientID string, messageFun mqtt.MessageHandler) (mqtt.Client, error) {
	mqtt.DEBUG = log.New(os.Stdout, "", 0)
	mqtt.ERROR = log.New(os.Stdout, "", 0)
	opts := mqtt.NewClientOptions().AddBroker(Addr).SetClientID(ClientID)

	opts.SetKeepAlive(30 * time.Second)

	// 设置消息回调处理函数
	opts.SetDefaultPublishHandler(messageFun)

	opts.SetPingTimeout(1 * time.Second)

	Client := mqtt.NewClient(opts)

	if token := Client.Connect(); token.Wait() && token.Error() != nil {
		return nil, token.Error()
		// panic(token.Error())
	}
	return Client, nil
}

func main() {
	//client, err := GetClient("tcp://14.29.243.119:1883", "gateway", nil)

	//mqtt.DEBUG = log.New(os.Stdout, "[debug]", 0)
	mqtt.ERROR = log.New(os.Stdout, "[error]", 0)
	opts := mqtt.NewClientOptions().AddBroker("tcp://14.29.243.119:1883").SetClientID(uuid.TimeUUID().String())
	opts.SetKeepAlive(time.Second * 60)
	opts.SetPingTimeout(time.Second * 3)
	opts.SetProtocolVersion(4)

	opts.SetDefaultPublishHandler(func(client mqtt.Client, message mqtt.Message) {
		fmt.Println(message.Topic())
		fmt.Println(message.Payload())
	})

	opts.SetConnectTimeout(time.Second * 60)
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}

	for {
		//message := uuid.FromTime(time.Now()).String()
		message := `{"Status":2,"UpdateTime":` + strconv.Itoa(int(time.Now().Unix())) + `}`
		fmt.Println("[message]", message)

		items := []string{"101000031", "101000030", "101000029", "101000028", "101000040"}
		for _, v := range items {
			token := client.Publish("/Gateway/Status/"+v, 1, false, message)

			if token.Wait() && token.Error() != nil {
				// // 断开连接
				client.Disconnect(250)
				time.Sleep(1 * time.Second)
				panic(token.Error())
			}
		}

		//token := client.Publish("/Gateway/Status/101000040", 1, false, message)
		//
		//if token.Wait() && token.Error() != nil {
		//	// // 断开连接
		//	client.Disconnect(250)
		//	time.Sleep(1 * time.Second)
		//	panic(token.Error())
		//}
		//
		//token = client.Publish("/Gateway/Status/101000028", 1, false, message)
		//
		//if token.Wait() && token.Error() != nil {
		//	// // 断开连接
		//	client.Disconnect(250)
		//	time.Sleep(1 * time.Second)
		//	panic(token.Error())
		//}
		time.Sleep(time.Second)
	}
}
